package com.prize.service.impl;

import cn.hutool.core.util.IdUtil;
import com.prize.config.LoginCodeEnum;
import com.prize.config.LoginProperties;
import com.prize.config.RedisConfig;
import com.prize.dtos.ResponseResult;
import com.prize.service.SysVerificationService;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @descriptions: 系统验证码
 * @author: yunqiang
 * @date: 2022/5/28 22:05
 */
@Service
public class SysVerificationServiceImpl implements SysVerificationService {


    @Resource
    private LoginProperties loginProperties;

    @Resource
    private RedisConfig redisConfig;

    /**
     * 获取系统验证码
     * @return
     */
    @Override
    public ResponseResult getCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = IdUtil.simpleUUID();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存
        redisConfig.getRedisTemplateByDb(1).opsForValue().set(uuid, captchaValue,loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseResult.successResult(imgResult);
    }
}
